<?php
/***********************************************
 *		SpeedPHP常用函数扩展类
 * 文件: /Extensions/spFun.php
 * 说明: 常用函数扩展类
 * 作者: Myxf
 * 更新: 2015年5月14日
 ***********************************************/

/**
 * 常用函数扩展类
 */
class spFun {

    //加密  
    function toacii($str,$key){
		//将明文内容转base64
		$str = base64_encode($str);
        $data = "";
       	$keystr = md5($key);
        for($i=0;$i<strlen($str);$i++){
           //取keystr的位数值转为acii值
           $num = ord($keystr[$i%32]);
           //将要解密内容转为acii值并加上动态num值
           $data .= chr(ord($str[$i])^$num);
        }
        //base64加密输出
        $data = base64_encode($data);
        $data = str_replace(array('+','/','='),array('-','_','*'),$data);
        return $data;
    }
    
    //解密
    function tostring($str,$key){
    	$str = str_replace(array('-','_','*'),array('+','/','='),$str);
    	//base64解密
    	$str = base64_decode($str);
    	$data = "";
       	$keystr = md5($key);
        for($i=0;$i<strlen($str);$i++){
            $data .= chr(ord($str[$i]) ^ ord($keystr[$i%32]));  
        }
        //base64解密，得到明文
        $data = base64_decode($data);
        return $data;
    }

    //将post数据解密
    function depost($post){
        $post = $this->tostring($post);
        $post = $this->convertUrlArray($post);
        return $post;
    }

    //url转数组
    function convertUrlArray($query)
    {
        $queryParts = explode('&', $query);
        $params = array();
        foreach ($queryParts as $param) {
            $item = explode('=', $param);
            $params[$item[0]] = $item[1];
        }
        return $params;
    }

    //发送短信
    function sendmsg($phone,$type,$msg){
        $http = spClass('spHttp');
        $url = "http://api.1cloudsp.com/api/v2/single_send";
        $accesskey = $GLOBALS['G_SP']['spSms']['accesskey'];
        $secret = $GLOBALS['G_SP']['spSms']['secret'];
        $sign = $GLOBALS['G_SP']['spSms']['sign'];
        $templateId = $type;
        $data = "accesskey=".$accesskey."&secret=".$secret."&sign=".$sign."&templateId=".$templateId."&mobile=".$phone."&content=".$msg;
        $http->vpost($url,$data);
    }
   
	/**
	 * 验证邮箱地址格式
	 */
	function isEmail($email)
	{
		if (preg_match("/[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-z]{2,4}/",$email,$mail))
		{
    		return true;
		}
		else
		{
    		return false;
		}
	}

	/**
	 * 验证用户名是否以字母开头
	 */
	function isUserNum($user)
	{
		if (preg_match("/^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){3,19}$/",$user,$username))
		{
    		return true;
		}
		else
		{
    		return false;
		}
	}

	/**
	 * 验证密码只能为数字和字母的组合
	 */
	function isPsd($psd)
	{
		if (preg_match("/^(\w){4,20}$/",$psd,$password))
		{
    		return true;
		}
		else
		{
    		return false;
		}
	}
	/**
	 * 转跳到url
	 */
	function url($url)
	{
		$code="<script language='javascript'>window.location.href='".$url."';</script>";
		return $code;
	}
	
    function toUrl($url="index.php",$info = "页面转向中...",$second=2){ 
		print "<html><head><title>页面转向中....</title>"; 
		print "<meta http-equiv='refresh' content='$second;url=$url'>"; 
		print '<style type="text/css">'; 
		print 'td { font-family: "Verdana", "Arial";font-size: 12px}'; 
		print 'A {COLOR: #000000; TEXT-DECORATION: none}'; 
		print '</style>'; 
		print '</head><body>'; 
		print '<table width="100%" border="0" align="center">'; 
		print " <tr>"; 
		print " <td height='200'> </td>"; 
		print " </tr>"; 
		print " <tr>"; 
		print " <td align='center'>"; 
		print '<table width="60%" border="0" cellpadding="8" bgcolor="#AA9FFF">'; //PHP开源代码 
		print " <tr>"; 
		print ' <td height="30" align="center">提示信息</td>'; 
		print " </tr>"; 
		print " <tr>"; 
		print "<td align='center'>$info</td>"; 
		print " </tr>"; 
		print " <tr>"; 
		print ' <td align="center">'; 
		print " 如果你的浏览器不支持自动跳转,请<a href='$url'>点击这里</a></td>"; 
		print " </tr>"; 
		print " </tr>"; 
		print " </table></td>"; 
		print " </tr>"; 
		print " <tr>"; 
		print ' <td height="200"> </td>'; 
		print " </tr>"; 
		print "</table>"; 
		print "</body></html>"; 
		exit; 
    }
	/**
	 * 弹出js提示框
	 */
	function msg($content)
	{
		$code="<script language='javascript'>alert('".$content."');</script>";
		return $code;
	}

	/**
	 * 返回上一页
	 */
	function back()
	{
			$code="<a href='javascript:window.history.go(-1);'>返回</a>";
			return $code;
	}

	/**
	 * 获取用户真实IP
	 */
    function getIP()
	{
		if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
		{
      		if ($_SERVER["HTTP_CLIENT_IP"])
      		{
            	$proxy = $_SERVER["HTTP_CLIENT_IP"];
      		}
      		else
      		{
           		$proxy = $_SERVER["REMOTE_ADDR"];
      		}
     		$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
		}
		else
		{
     		if (isset($_SERVER["HTTP_CLIENT_IP"]))
     		{
            	$ip = $_SERVER["HTTP_CLIENT_IP"];
      		}
      		else
      		{
           		$ip = $_SERVER["REMOTE_ADDR"];
      		}
		}
		return $ip;
	}

	/**
	 * 字符串截取
	 */
	function strSub($string, $sublen, $start)
	{
		$pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
		preg_match_all($pa, $string, $t_string);

		if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen));
		return join('', array_slice($t_string[0], $start, $sublen));
	}

	/**
	 * 首尾截取字符串
	 */
	function strCut($string,$strstart,$strend)
    {
        $v_a=explode($strstart, $string);
        $v_a=explode($strend, $v_a[1]);
        return $v_a[0];
    }

	/**
	 * 字符串替换
	 */
	function strReplace($str)
	{
		$str=str_replace("<","&lt;",$str);
		$str=str_replace(">","&gt;",$str);
		$str=str_replace("object","",$str);
		$str=str_replace("script","",$str);

		return $str;
	}

	/**
	 * 转义提交数据中的HTML代码
	 */
	function clearHTML($val)
	{
		return ltrim(chop(htmlspecialchars($val)));
	}

	/**
	 * 清空字符串中的HTML标签
	 */
	function clearLabel($html)
	{
		$search = array ("'<script[^>]*?>.*?</script>'si", "'<[/!]*?[^<>]*?>'si", "'([rn])[s]+'", "'&(quot|#34);'i", "'&(amp|#38);'i", "'&(lt|#60);'i", "'&(gt|#62);'i", "'&(nbsp|#160);'i", "'&(iexcl|#161);'i", "'&(cent|#162);'i", "'&(pound|#163);'i", "'&(copy|#169);'i", "'&#(d+);'e");
     	$replace = array ("", "", "\1", "\"", "&", "<", ">", " ", chr(161), chr(162), chr(163), chr(169), "chr(\1)");

     	return preg_replace($search, $replace, $html);
	}

	/**
	* 创建多级目录
	*/
	function createDir($dir)
	{
		if(!is_dir($dir))
		{
			if(!createDir(dirname($dir)))
			{
				return false;
			}
			if(!mkdir($dir,0777))
			{
				return false;
			}
		}
		return true;
	}
    
    // 一次只能创建一级目录,成功返回1
	function createDir0($dirname,$mode=0777)
	{
			if(is_null($dirname) || $dirname=="")	return false;
			if(!is_dir($dirname))
			{
				return mkdir($dirname,$mode);
			}
	}
	
	//删除目录包括有文件	
	function delDir($dirname)
	{
			if(isExists($dirname) and is_dir($dirname))
			{
				if(!$dirhandle=opendir($dirname)) return false;
				while(($file=readdir($dirhandle))!==false)
				{
					if($file=="." or $file=="..")	continue;
					$file=$dirname.DIRECTORY_SEPARATOR.$file;  //表示$file是$dir的子目录
					if(is_dir($file))
					{
						delDir($file);
					}
					else
					{
						unlink($file);
					}
				}
				closedir($dirhandle);
				return rmdir($dirname);
			}
			else	return false;
	}

	//复制文件
	function copyFile($srcfile,$newfile)
	{
			if(is_file($srcfile))
			{
				if(!file_exists($newfile))
				return copy($srcfile,$newfile);
			}
			else	return false;
	}

	//删除文件
    function delFile($filename)
   	{
   	 		if(isExists($filename) and is_file($filename))
   	 		{
   	 			return unlink($filename);
   	 		}
   	 		else	return false;
   	}

   	//将字符串写入文件
    function writeStr($filename,$str)
   	{
   	 		if(function_exists(file_put_contents))
   	 		{
   	 			file_put_contents($filename,$str);
   	 		}
   	 		else
   	 		{
   	 			$fp=fopen($filename,"wb");
   	 			fwrite($fp,$str);
   	 			fclose($fp);
   	 		}
   	} 	
	
}  	 	
?>